package pl.register.android.database.crud;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import pl.register.android.database.tables.HomeworkDBTable;
import pl.register.android.homework.Homework;
import pl.register.android.homework.HomeworkTopic;
import pl.register.android.lesson.Lesson;
import pl.register.android.rating.Rating;

/**
 * @author Mateusz Strzelecki
 * @since 2013-04-26
 */
public class HomeworkCRUD {

    private SQLiteDatabase database;

    public HomeworkCRUD(SQLiteDatabase database) {
        this.database = database;
    }

    public Homework findHomeworkBy(Long lessonId, HomeworkTopic homeworkTopic) {
        Homework homework = null;
        String where = HomeworkDBTable.FK_LESSON_ID + " = " + lessonId;
        Cursor cursor = database.query(HomeworkDBTable.TABLE_NAME, null, where, null, null, null, null);
        if (cursor.moveToFirst()) {
            Long homeworkId = cursor.getLong(cursor.getColumnIndex(HomeworkDBTable.ID));
            int homeworkIsDoneInt = cursor.getInt(cursor.getColumnIndex(HomeworkDBTable.IS_DONE));
            String homeworkRatingString = cursor.getString(cursor.getColumnIndex(HomeworkDBTable.RATING));

            boolean isDone = homeworkIsDoneInt == 1;
            Rating rating = Rating.valueOf(homeworkRatingString);
            homework = new Homework(homeworkId, homeworkTopic, isDone, rating);
        }
        cursor.close();
        return homework;
    }

    public Homework insertHomework(Homework homework, HomeworkTopic homeworkTopic, Lesson lesson) {
        ContentValues insertValues = new ContentValues();
        insertValues.put(HomeworkDBTable.IS_DONE, homework.isDone());
        insertValues.put(HomeworkDBTable.RATING, homework.getRating().toString());
        insertValues.put(HomeworkDBTable.FK_LESSON_ID, lesson.getId());
        insertValues.put(HomeworkDBTable.FK_HOMEWORK_TOPIC_ID, homeworkTopic.getId());
        long rowId = database.insert(HomeworkDBTable.TABLE_NAME, null, insertValues);
        homework.setId(rowId);
        return homework;
    }

    public Homework updateHomework(Homework homework) {
        String where = HomeworkDBTable.ID + " = " + homework.getId();
        ContentValues updateValues = new ContentValues();
        updateValues.put(HomeworkDBTable.IS_DONE, homework.isDone());
        updateValues.put(HomeworkDBTable.RATING, homework.getRating().toString());
        long rowId = database.update(HomeworkDBTable.TABLE_NAME, updateValues, where, null);
        return homework;
    }

    public void delete(Lesson lesson) {
        String where = HomeworkDBTable.FK_LESSON_ID + " = " + lesson.getId();
        int res = database.delete(HomeworkDBTable.TABLE_NAME, where, null);
    }

}